﻿namespace LiteBlog.Repositories
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml.Linq;

    using LiteBlog.Common;
    using LiteBlog.Common.Components;
    using LiteBlog.Common.Entities;
    using LiteBlog.Repositories.Contracts;
    using LiteBlog.Repositories.Helpers;
    using LiteBlog.Common.Enums;
    using LiteBlog.Repositories.Framework;
    using LiteBlog.Repositories.Common;

    public class CategoryRepository : StandardRepository<Category>, ICategoryRepository
    {
        
        public CategoryRepository(IDataContext context, IXmlHelper xmlHelper) : base(context, xmlHelper)
        {
            _path = context.GetPath(DataStoreType.Category, null);
            _elementName = Elem.Category;
        }

        protected override Category GetEntity(XElement elem)
        {
            var cat = new Category();
            cat.CatID = elem.Attribute(Attr.Id).Value;
            cat.Name = elem.Attribute(Attr.Name).Value;
            cat.Count = (int)elem.Attribute(Attr.Count);
            cat.Order = (int)elem.Attribute(Attr.Order);
            return cat;
        }

        protected override XElement GetElement(Category item)
        {
            return new XElement(
                   Elem.Category,
                   new XAttribute(Attr.Id, item.CatID),
                   new XAttribute(Attr.Name, item.Name),
                   new XAttribute(Attr.Count, item.Count),
                   new XAttribute(Attr.Order, item.Order));
        }

        protected override void UpdateElement(XElement elem, Category item)
        {
            elem.SetAttributeValue(Attr.Id, item.CatID);
            elem.SetAttributeValue(Attr.Name, item.Name);
            elem.SetAttributeValue(Attr.Order, item.Order);
            elem.SetAttributeValue(Attr.Count, item.Count);
        }

        protected override string GetId(Category item)
        {
            return item.CatID;
        }

        protected override void SetId(Category item, string id)
        {
            item.CatID = id;
        }


        internal List<Category> GetCategories(string csvIds)
        {
            var filteredCategories = new List<Category>();
            var catIds = csvIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (catIds.Length > 0)
            {
                var categories = Get();
                filteredCategories = categories.Where(category => 
                                                    catIds.Any(catId => catId.Trim().Equals(category.CatID)))
                                                .ToList();
            }
            return filteredCategories;
        }
    }
}